package cn.org.timespace.easyframe.util.tag;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 此类用于完成字典表的翻译功能（将code转换成值）
 * 
 * @author 陈灿
 * 
 */
public class CodeToNameTag extends BodyTagSupport {

	private static final Log log = LogFactory.getLog(CodeToNameTag.class);

	private static final long serialVersionUID = 3984693398166947061L;

	private static enum Type {
		table, // 直接从字典表里面获取数据
		sql    // 通过字典表里面配置的sql语句获取数据
	}
	
	public CodeToNameTag() {
		super();
	}

	public void release() {
		super.release();
	}

	// 类型 不是必须的
	private String type;

	// 分组名 必须的
	private String groupname;

	// 需翻译的值 必须的
	private String translateValue;

	// 是否显示value 不是必须的 默认不显示value 只显示name
	private boolean link;

	public int doStartTag() {
		return SKIP_BODY;
	}

	public int doEndTag() throws JspTagException {

		try {
			
			if (type == null) {
				type = Type.table.toString();
			}
			
			if (groupname != null && groupname.trim().length() > 0 
					&& translateValue != null && translateValue.trim().length() > 0) {
				
				String resName = "";
				
				if (Type.table.toString().equalsIgnoreCase(type)) {
					resName = Translate.getInstance().getNameByTable(getGroupname(), getTranslateValue());
				} else {
					resName = Translate.getInstance().getNameBySql(getGroupname(), getTranslateValue());
				}
				
				String display = "";
				if (link) {
					display = translateValue + " -- " + resName;
				} else {
					display = resName;
				}

				pageContext.getOut().print(display);
				
			}else{
				if (log.isErrorEnabled())
					log.error("属性groupname、translateValue不能为空。");
			}
			
			
		} catch (Exception ex) {
			if (log.isErrorEnabled())
				log.error("根据<" + getGroupname() + ">生成下拉框出错，原因是："
						+ ex.getMessage());
			ex.printStackTrace();
		}

		return EVAL_PAGE;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getGroupname() {
		return groupname;
	}

	public void setGroupname(String groupname) {
		this.groupname = groupname;
	}

	public String getTranslateValue() {
		return translateValue;
	}

	public void setTranslateValue(String translateValue) {
		this.translateValue = translateValue;
	}

	public boolean isLink() {
		return link;
	}

	public void setLink(boolean link) {
		this.link = link;
	}

}
